<template>
  <view class="map-container">
    <!-- 顶部点位列表 -->
    <view class="point-tabs-container">
      <scroll-view 
        ref="tabsScrollView"
        class="point-tabs-scroll" 
        scroll-x="true" 
        show-scrollbar="false"
        :scroll-left="scrollLeft"
      >
        <view class="point-tabs">
          <view 
            v-for="(point, index) in pointList" 
            :key="point.id"
            :id="`tab-${point.id}`"
            class="point-tab"
            :class="{ 'active': selectedPointId === point.id }"
            @click="selectPoint(point, index)"
          >
            <view class="tab-content">
              <image 
                v-if="point.icon" 
                :src="point.icon" 
                class="tab-icon"
                mode="aspectFit"
              ></image>
              <u-icon v-else name="map-pin" size="16" color="#666"></u-icon>
              <text class="tab-text">{{ point.name }}</text>
            </view>
          </view>
        </view>
      </scroll-view>
    </view>

    <!-- 腾讯地图容器 -->
    <map
      id="map"
      class="map"
      :latitude="mapData.latitude"
      :longitude="mapData.longitude"
      :scale="mapData.scale"
      :markers="markers"
      :show-location="true"
      @markertap="onMarkerTap"
      @regionchange="onRegionChange"
      @load="onMapLoad"
    ></map>
    
    <!-- 加载状态 -->
    <view v-if="loading" class="loading-overlay">
      <view class="loading-content">
        <!-- <u-loading-icon mode="spinner" size="40"></u-loading-icon> -->
        <text class="loading-text">正在加载地图数据...</text>
      </view>
    </view>
    
    <!-- 动画图标 -->
    <view 
      v-if="showAnimatedIcon" 
      class="animated-icon"
      :class="{ 'icon-arrived': iconArrived }"
      :style="iconStyle"
      @click="showLocationPopup"
    >
      <view class="icon-content">
        <image 
          v-if="mapData.icon" 
          :src="mapData.icon" 
          class="icon-image"
          mode="aspectFit"
        ></image>
        <u-icon v-else name="map-pin" size="24" color="#007aff"></u-icon>
      </view>
    </view>
    
    <!-- 信息弹窗 -->
    <u-popup
      v-model="showPopup"
      mode="center"
      :border-radius="16"
      :closeable="true"
      @close="closePopup"
    >
      <view class="popup-content">
        <view class="popup-header">
          <text class="popup-title">{{ popupData.title }}</text>
        </view>
        <view class="popup-body">
          <image 
            v-if="popupData.image" 
            :src="popupData.image" 
            class="popup-image"
            mode="aspectFill"
          ></image>
          <scroll-view class="popup-description-scroll" scroll-y>
            <!-- <text class="popup-description">{{ popupData.description }}</text> -->
            <u-parse :html="popupData.description"></u-parse>
          </scroll-view>
        </view>
        <view class="popup-footer">
          <u-button 
            type="primary" 
            size="medium"
            @click="closePopup"
          >
            确定
          </u-button>
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script>
export default {
  name: 'MapPage',
  data() {
    return {
      loading: true,
      pointList: [], // 点位列表
      selectedPointId: null, // 当前选中的点位ID
      scrollLeft: 0, // 滚动位置
      mapData: {
        latitude: 39.908823,
        longitude: 116.397470,
        scale: 12,
        content: '',
        icon: '',
        name: ''
      },
      markers: [],
      showPopup: false,
      popupData: {
        title: '',
        description: '',
        image: ''
      },
      // 动画图标相关
      showAnimatedIcon: false,
      iconArrived: false,
      iconStyle: {
        left: '-120px',
        top: '50%'
      },
    }
  },
  
  onLoad({ id }) {
    console.log('id', id)
    this.initMap(id)
  },
  
  methods: {
    // 初始化地图
    async initMap(id) {
      try {
        this.loading = true
        
        // 获取点位列表
        await this.getPointList()
        
        // 如果有传入的id，使用该id；否则使用第一个点位
        const targetId = id || (this.pointList.length > 0 ? this.pointList[0].id : null)
        
        if (targetId) {
          // 确保选中状态正确设置
          this.selectedPointId = targetId
          
          // 找到选中点位的索引并滚动到对应位置
          const selectedIndex = this.pointList.findIndex(point => point.id === targetId)
          if (selectedIndex !== -1) {
            this.scrollToTab(selectedIndex)
          }
          
          // 获取位置坐标
          await this.getLocationCoordinates(targetId)
          
          // 设置地图标记
          this.setMapMarkers()
          
          // 地图居中并放大
          this.centerAndZoomMap()
          
          // 重置图标位置到外部
          this.resetIconPosition()
          
          // 开始图标动画
          setTimeout(() => {
            this.startIconAnimation()
          }, 500)
        }
        
      } catch (error) {
        console.error('地图初始化失败:', error)
        uni.showToast({
          title: '地图加载失败',
          icon: 'none'
        })
      } finally {
        this.loading = false
      }
    },
    
    // 获取点位列表
    async getPointList() {
      try {
        const response = await this.$api.getPointList()
        if (response && response.length > 0) {
          this.pointList = response
          // 如果没有选中任何点位，默认选中第一个点位
          if (!this.selectedPointId) {
            this.selectedPointId = response[0].id
          }
        }
      } catch (error) {
        console.error('获取点位列表失败:', error)
        uni.showToast({
          title: '获取点位列表失败',
          icon: 'none'
        })
      }
    },
    
    // 选择点位
    async selectPoint(point, index) {
      if (this.selectedPointId === point.id) return
      
      try {
        this.selectedPointId = point.id
        this.loading = true
        
        // 自动滚动到选中的tab
        this.scrollToTab(index)
        
        // 获取选中点位的位置坐标
        await this.getLocationCoordinates(point.id)
        
        // 设置地图标记
        this.setMapMarkers()
        
        // 地图平移到新位置
        this.moveToLocation()
        
        // 重置图标动画状态
        this.showAnimatedIcon = false
        this.iconArrived = false
        
        // 重置图标位置到外部（从右侧进入）
        this.resetIconPosition()
        
        // 延迟开始图标动画，让地图先平移完成
        setTimeout(() => {
          this.startIconAnimation()
        }, 500)
        
      } catch (error) {
        console.error('切换点位失败:', error)
        uni.showToast({
          title: '切换点位失败',
          icon: 'none'
        })
      } finally {
        this.loading = false
      }
    },
    
    // 自动滚动到选中的tab
    scrollToTab(index) {
      // 延迟执行，确保DOM已渲染
      this.$nextTick(() => {
        // 计算每个tab的宽度（包括间距）
        const tabWidth = 120 // 每个tab的宽度（根据CSS中的padding: 8px 16px计算）
        const tabGap = 12 // tab之间的间距
        const containerPadding = 15 // 容器左右padding
        
        // 计算选中tab的位置
        const tabPosition = index * (tabWidth + tabGap) + containerPadding
        
        // 让选中的tab滚动到最左侧
        const targetScrollLeft = Math.max(0, tabPosition - containerPadding)
        
        // 设置滚动位置
        this.scrollLeft = targetScrollLeft
        
        console.log(`滚动到tab ${index}, 位置: ${targetScrollLeft}`)
      })
    },
    
    // 地图加载完成
    onMapLoad() {
      console.log('地图加载完成')
    },
    
    // 获取位置坐标
    async getLocationCoordinates(id) {
      // 调用API接口获取经纬度
      const response = await this.$api.getMapLocation(id)
        if (response) {
          this.mapData.title = response.name
          this.mapData.latitude = response.latitude
          this.mapData.longitude = response.longitude
          this.mapData.content = response.content
          this.mapData.icon = response.icon
          
          // 如果有位置名称，也可以保存
          if (response.name) {
            this.popupData.title = response.name
            this.popupData.description = response.content
          }
      }
    },
    
    // 设置地图标记
    setMapMarkers() {
      this.markers = [{
        id: 1,
        latitude: this.mapData.latitude,
        longitude: this.mapData.longitude,
        iconPath: '/static/images/map-marker.svg',
        width: 32,
        height: 32,
        callout: {
          content: this.popupData.title,
          color: '#ffffff',
          fontSize: 12,
          borderRadius: 6,
          bgColor: '#007aff',
          padding: 8,
          display: 'ALWAYS',
          textAlign: 'center'
        }
      }]
    },
    
    // 地图居中并放大
    centerAndZoomMap() {
      this.mapData.scale = 15
      
      // 使用地图上下文进行更精确的控制
      const mapContext = uni.createMapContext('map', this)
      mapContext.moveToLocation({
        latitude: this.mapData.latitude,
        longitude: this.mapData.longitude,
        success: () => {
          console.log('地图居中成功')
        },
        fail: (error) => {
          console.error('地图居中失败:', error)
        }
      })
    },
    
    // 地图平移到指定位置
    moveToLocation() {
      this.mapData.scale = 15
      
      const mapContext = uni.createMapContext('map', this)
      mapContext.moveToLocation({
        latitude: this.mapData.latitude,
        longitude: this.mapData.longitude,
        success: () => {
          console.log('地图平移成功')
        },
        fail: (error) => {
          console.error('地图平移失败:', error)
        }
      })
    },
    
    // 重置图标位置到外部
    resetIconPosition() {
      const screenWidth = uni.getSystemInfoSync().screenWidth
      const screenHeight = uni.getSystemInfoSync().screenHeight
      
      // 随机选择进入方向（考虑目标位置向下偏移）
      const directions = [
        // 从右侧进入
        {
          left: `${screenWidth + 120}px`,
          top: `${screenHeight / 2 + 10}px` // 与目标位置保持一致
        },
        // 从左侧进入
        {
          left: `-120px`,
          top: `${screenHeight / 2 + 10}px` // 与目标位置保持一致
        },
        // 从上方进入
        {
          left: `${screenWidth / 2 - 60}px`,
          top: `-120px`
        },
        // 从下方进入
        {
          left: `${screenWidth / 2 - 60}px`,
          top: `${screenHeight + 120}px`
        }
      ]
      
      // 随机选择一个方向
      const randomDirection = directions[Math.floor(Math.random() * directions.length)]
      
      this.iconStyle = {
        ...randomDirection,
        transition: 'none' // 重置时不要过渡动画
      }
    },
    
    // 开始图标动画
    startIconAnimation() {
      this.showAnimatedIcon = true
      
      // 延迟开始移动动画，让图标先显示在外部位置
      setTimeout(() => {
        this.moveIconToTarget()
      }, 100)
    },
    
    // 移动图标到目标位置
    moveIconToTarget() {
      // 计算目标位置（屏幕中心偏下，避免遮挡地图标记标题）
      const screenWidth = uni.getSystemInfoSync().screenWidth
      const screenHeight = uni.getSystemInfoSync().screenHeight
      
      this.iconStyle = {
        left: `${screenWidth / 2 - 60}px`,
        top: `${screenHeight / 2 + 10}px`, // 向下移动40px，避免遮挡地图标记
        transition: 'all 1.8s cubic-bezier(0.175, 0.885, 0.32, 1.275)' // 更流畅的缓动效果
      }
      // 动画完成后显示弹窗
      setTimeout(() => {
        this.iconArrived = true
        this.showLocationPopup()
      }, 1800)
    },
    
    // 显示位置弹窗
    showLocationPopup() {
      this.showPopup = true
    },
    
    // 标记点击事件
    onMarkerTap(e) {
      const markerId = e.detail.markerId
      console.log('点击标记:', markerId)
      
      // 可以在这里处理标记点击逻辑
      this.showLocationPopup()
    },
    
    // 地图区域变化事件
    onRegionChange(e) {
      if (e.type === 'end') {
        console.log('地图区域变化:', e.detail)
      }
    },
    
    // 关闭弹窗
    closePopup() {
      this.showPopup = false
    }
  }
}
</script>

<style lang="scss" scoped>
.map-container {
  position: relative;
  width: 100%;
  height: 100vh;
  background-color: #f5f5f5;
  overflow: hidden;
}

// 顶部点位列表样式
.point-tabs-container {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 1001;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 10px 0;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.point-tabs-scroll {
  width: 100%;
  white-space: nowrap;
}

.point-tabs {
  display: flex;
  padding: 0 15px;
  gap: 12px;
}

.point-tab {
  flex-shrink: 0;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 20px;
  padding: 8px 16px;
  transition: all 0.3s ease;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.3);
  
  &.active {
    background: rgba(255, 255, 255, 0.9);
    transform: scale(1.05);
    box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
  }
  
  .tab-content {
    display: flex;
    align-items: center;
    gap: 6px;
    
    .tab-icon {
      width: 20px;
      height: 20px;
      border-radius: 50%;
    }
    
    .tab-text {
      font-size: 14px;
      font-weight: 500;
      color: #ffffff;
      white-space: nowrap;
    }
  }
  
  &.active .tab-content .tab-text {
    color: #333;
  }
}

.map {
  width: 100%;
  height: 100%;
}

.loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  animation: fadeIn 0.5s ease-in-out;
}

.loading-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 20px;
  background-color: rgba(255, 255, 255, 0.95);
  padding: 30px;
  border-radius: 16px;
  box-shadow: 0 10px 40px rgba(0, 0, 0, 0.2);
}

.loading-text {
  font-size: 16px;
  color: #333;
  font-weight: 500;
}

.animated-icon {
  position: fixed;
  z-index: 999;
  width: 120px;
  height: 120px;
  display: flex;
  align-items: center;
  justify-content: center;
  // background: linear-gradient(135deg, #007aff 0%, #5ac8fa 100%);
  border-radius: 50%;
  box-shadow: 0 8px 30px rgba(0, 122, 255, 0.4);
  border: 3px solid #ffffff;
  animation: iconEnter 0.8s ease-out forwards, iconFloat 2s ease-in-out infinite 0.8s;
  opacity: 0;
  transform: scale(0.3) rotate(-180deg);
  
  .icon-content {
    display: flex;
    align-items: center;
    justify-content: center;
    
    .icon-image {
      width: 120px;
      height: 120px;
      border-radius: 50%;
    }
  }
  
  &.icon-arrived {
    animation: iconBounce 0.8s ease-in-out, iconFloat 2s ease-in-out infinite;
    opacity: 1;
    transform: scale(1);
  }
}

@keyframes iconFloat {
  0%, 100% {
    transform: translateY(0px);
  }
  50% {
    transform: translateY(-5px);
  }
}

@keyframes iconEnter {
  0% {
    opacity: 0;
    transform: scale(0.3) rotate(-180deg);
  }
  50% {
    opacity: 0.8;
    transform: scale(1.1) rotate(0deg);
  }
  100% {
    opacity: 1;
    transform: scale(1) rotate(0deg);
  }
}

@keyframes iconBounce {
  0%, 20%, 50%, 80%, 100% {
    transform: translateY(0) scale(1);
  }
  40% {
    transform: translateY(-15px) scale(1.1);
  }
  60% {
    transform: translateY(-8px) scale(1.05);
  }
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.popup-content {
  width: 85vw;
  background-color: #ffffff;
  overflow: hidden;
//   box-shadow: 0 20px 60px rgba(0, 0, 0, 0.2);
//   animation: popupSlideIn 0.4s ease-out;
}

@keyframes popupSlideIn {
  from {
    opacity: 0;
    transform: scale(0.8) translateY(30px);
  }
  to {
    opacity: 1;
    transform: scale(1) translateY(0);
  }
}

.popup-header {
  padding: 24px 24px 20px;
  border-bottom: 1px solid #f0f0f0;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  position: relative;
  
  &::after {
    content: '';
    position: absolute;
    bottom: -1px;
    left: 0;
    right: 0;
    height: 1px;
    background: linear-gradient(90deg, transparent 0%, #f0f0f0 50%, transparent 100%);
  }
}

.popup-title {
  font-size: 20px;
  font-weight: 600;
  color: #ffffff;
  text-align: center;
}

.popup-body {
  padding: 10px;
}

.popup-image {
  width: 100%;
  height: 180px;
  border-radius: 12rpx;
}
.popup-description-scroll {
    max-height: 50vh;
    overflow: hidden;
    font-size: 15px;
    color: #555;
    line-height: 1.7;
    text-align: justify;
    margin-bottom: 8px;
}
.popup-description {
  font-size: 15px;
  color: #555;
  line-height: 1.7;
  text-align: justify;
  margin-bottom: 8px;
}

.popup-footer {
  padding: 24rpx;
  display: flex;
  justify-content: center;
  border-top: 1px solid #f0f0f0;
  background: linear-gradient(180deg, #fafafa 0%, #f5f5f5 100%);
}

// 响应式设计
@media (max-width: 375px) {
  .popup-content {
    width: 300px;
  }
  
  .popup-header,
  .popup-body,
  .popup-footer {
    padding: 20px;
  }
  
  .popup-title {
    font-size: 18px;
  }
  
  .popup-description {
    font-size: 14px;
  }
  
  .point-tab {
    padding: 6px 12px;
    
    .tab-content .tab-text {
      font-size: 12px;
    }
  }
}
</style> 